package com.xywy.bloodandroid.act;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.AddNumData;
import com.xywy.bloodandroid.bean.AddNumberDetailsData;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.VolleyManager;

/**
 * 预约详情
 */
public class MyAddNumberDetailsActivity extends BaseActivity {

	protected static final int FAIL = 0;
	protected static final int SUCCESS = 1;
	private static final String TAG = "MyAddNumberDetailsActivity";
	private TextView middle_title;
	private RelativeLayout left_img;
	private Button tv_tip; // 提示
	private TextView tv_hospital; // 医院
	private TextView tv_name; // 名称
	private TextView tv_doctor_time; // 就诊时间
	private TextView tv_doctor_type; // 就诊类型
	private TextView tv_price; // 挂号费
	private TextView tv_state; // 预约状态
	private TextView tv_position; // 就诊地址
	private Button bt_cancle; // 取消按钮
	private LinearLayout ll_root;// 布局根目录；
	private TextView tv_fail; // 失败

	private AddNumData data;
	private int state; // 订单状态 (1:待审核 2:等待就诊 3:未通过审核 4:预约取消 5:成功就诊 6:爽约
						// 7:取消就诊)

	private SharedPreferences sp;
	private Editor editor;

	@Override
	protected void initView(Bundle savedInstanceState) {
		// state = getPlusIdState();
		data = getData();
		setContentView(R.layout.activity_add_num_details);
		tv_fail = (TextView) findViewById(R.id.tv_fail);
		middle_title = (TextView) findViewById(R.id.middle_title);
		tv_tip = (Button) findViewById(R.id.tv_tip);
		middle_title.setText("预约详情");
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		ll_root = (LinearLayout) findViewById(R.id.ll_root);
		tv_hospital = (TextView) findViewById(R.id.tv_hospital);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_doctor_time = (TextView) findViewById(R.id.tv_doctor_time);
		tv_doctor_type = (TextView) findViewById(R.id.tv_doctor_type);
		tv_price = (TextView) findViewById(R.id.tv_price);
		tv_state = (TextView) findViewById(R.id.tv_state);
		tv_position = (TextView) findViewById(R.id.tv_position);
		bt_cancle = (Button) findViewById(R.id.bt_cancle);

	}

	/**
	 * 从上一个页面带过来是数据
	 * 
	 * @return
	 */
	private AddNumData getData() {
		Intent intent = getIntent();
		return (AddNumData) intent.getSerializableExtra("data");
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		tv_tip.setOnClickListener(this);
		bt_cancle.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		// state = Integer.parseInt(data.getState());
		// 1:待审核 2:等待就诊 3:未通过审核 5:成功就诊 6:爽约 7:取消就诊 8:审核前取消 9审核后取消
		getDetails();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_img:
			MyAddNumberDetailsActivity.this.finish();
			break;
		case R.id.tv_tip:
			if (state != 4)
				getPlusId();
			break;
		case R.id.bt_cancle:
			canclePlus();
			break;
		default:
			break;
		}

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				UIUtil.DissDialog(context, waittingDialog);
				showToast("获取失败");
				tv_fail.setVisibility(View.VISIBLE);
				ll_root.setVisibility(View.GONE);
				break;
			case SUCCESS:
				UIUtil.DissDialog(context, waittingDialog);
				tv_fail.setVisibility(View.GONE);
				ll_root.setVisibility(View.VISIBLE);
				AddNumberDetailsData dataDetails = (AddNumberDetailsData) msg.obj;
				if (dataDetails == null || dataDetails.toString().length() < 1)
					return;
				state = Integer.parseInt(dataDetails.getState());
				// 等待就诊 ，取票可以点击
				if (state == 2 && time(dataDetails)) {
					tv_tip.setClickable(true);
					tv_tip.setBackgroundResource(R.drawable.login_button_selector);
				} else {
					tv_tip.setClickable(false);
					tv_tip.setBackgroundResource(R.drawable.login_button_press);
				}
				if (state != 1 || state != 2) {
					bt_cancle.setClickable(false);
					bt_cancle
							.setBackgroundResource(R.drawable.login_button_press);
				} else {
					bt_cancle.setClickable(true);
					bt_cancle
							.setBackgroundResource(R.drawable.login_button_selector);
				}

				tv_price.setText("挂号费：" + dataDetails.getRegister());// 挂号费
				tv_state.setText("预约状态：" + getStateStr(state));
				tv_position
						.setText("就诊地址：" + dataDetails.getHospital_address());
				tv_hospital.setText(dataDetails.getHopital());
				tv_name.setText("专家姓名：" + dataDetails.getExpert());
				tv_doctor_time.setText("预约就诊时间：" + dataDetails.getTodate());
				tv_doctor_type.setText("门诊类型：" + dataDetails.getDepart());
//				time(dataDetails);
				if (state != 4) {
					tv_tip.setText("领取专家号凭证 \n(请在就诊前一天16点之前领取加号凭证)");
					bt_cancle.setVisibility(View.VISIBLE);
				} else {
					tv_tip.setText("您的加号已取消");
					bt_cancle.setVisibility(View.GONE);
				}
				break;
			}
		}
		/*根据当前状态显示内容*/
		private CharSequence getStateStr(int state) {
			switch (state) {
			case 1:
				return "待审核";
			case 2:
				return "等待就诊";
			case 3:
				return "未通过审核";
			case 5:
				return "成功就诊";
			case 6:
				return "爽约";
			case 7:
				return "取消就诊";
			case 8:
				return "审核前取消";
			case 9:
				return "审核后取消";
			}
			return "";
		};
	};

	/**
	 * 获取加号页面详情
	 */
	private void getDetails() {

		String sign = null;
//		String testUserId = "8519661";
		String testUserId = User.getInstance(context).getUserid();
		try {
			sign = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=zhuanjia&fun=PlusDetail&tag="
				+ Constants.tag
				+ "&sign="
				+ sign
				+ "&user_id="
				+ User.getInstance(context).getUserid()
				+ "&plus_id=" + data.getPlus_id();
		GetRequest<String> getRequest = new GetRequest<String>(url,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						showToast("信息获取失败");
						Message msg = Message.obtain();
						msg.what = FAIL;
						handler.sendMessage(msg);
					}

					@Override
					public void onSuccess(String response) {
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(response);
							int code = jsonObject.getInt("code");
							if (code == 10000) {
								String data = jsonObject.getString("data");

								AddNumberDetailsData dataDetails = JsonUtil
										.parseJsonToBean(data,
												AddNumberDetailsData.class);
								Message msg = Message.obtain();
								msg.what = SUCCESS;
								msg.obj = dataDetails;
								handler.sendMessage(msg);

							} else {
								Message msg = Message.obtain();
								msg.what = FAIL;
								handler.sendMessage(msg);
							}
						} catch (JSONException e) {
							Message msg = Message.obtain();
							msg.what = FAIL;
							handler.sendMessage(msg);
							e.printStackTrace();
						}

					}

				});

		getRequest.setIsParseJson(false);
		executeRequest(getRequest);
		// VolleyManager.addRequest(getRequest, TAG);

	}

	/**
	 * 领取专家号凭证
	 */
	private void getPlusId() {
		String sign = null;
		try {
			sign = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=zhuanjia&fun=PlusVoucher&tag="
				+ Constants.tag
				+ "&sign="
				+ sign
				+ "&user_id="
				+ User.getInstance(context).getUserid()
				+ "&plus_id=" + data.getPlus_id();

		GetRequest<String> getRequest = new GetRequest<String>(url,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						showToast("领取失败");
					}

					@Override
					public void onSuccess(String response) {

						try {
							JSONObject jsonObject = new JSONObject(response);
							int code = jsonObject.getInt("code");
							if (code == 10000) {
								Intent intent = new Intent(
										MyAddNumberDetailsActivity.this,
										AddNumSendMsgActvity.class);
								startActivity(intent);
							} else {
								Intent intent = new Intent(
										MyAddNumberDetailsActivity.this,
										AddNumSendMsgActvity.class);
								startActivity(intent);
								showToast(jsonObject.getString("msg"));
							}

						} catch (JSONException e) {
							showToast("领取失败");
							e.printStackTrace();
						}

					}
				});
		getRequest.setIsParseJson(false);
		VolleyManager.addRequest(getRequest, TAG);
	}

	/**
	 * 取消加号
	 */
	private void canclePlus() {
		String sign = null;
//		String testUserId = "8519661";
		String testUserId = User.getInstance(context).getUserid();
		try {
			sign = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=zhuanjia&fun=CancelPlus&tag="
				+ Constants.tag
				+ "&sign="
				+ sign
				+ "&user_id="
				+ User.getInstance(context).getUserid()
				+ "&plus_id=" + data.getPlus_id();
		GetRequest<String> getRequest = new GetRequest<String>(url,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						showToast("取消失败");
					}

					@Override
					public void onSuccess(String response) {

						try {
							JSONObject jsonObject = new JSONObject(response);
							int code = jsonObject.getInt("code");
							if (code == 10000) {
								tv_tip.setText("您的预约已经取消");
								bt_cancle.setVisibility(View.GONE);
								getDetails();
							} else {
								showToast(jsonObject.getString("msg"));
							}

						} catch (JSONException e) {
							showToast("领取失败");
							e.printStackTrace();
						}

					}
				});
		getRequest.setIsParseJson(false);
		VolleyManager.addRequest(getRequest, TAG);
	}

	/**
	 * 判断时间是否是预约前一天的0-16点之间
	 * 
	 * @param dataDetails
	 * @return
	 */
	private boolean time(AddNumberDetailsData dataDetails) {
		String date = dataDetails.getTodate().substring(0, 10);
		long time;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = null;
		try {
			d = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		time = d.getTime();
		// 预约的日期
		Calendar c1 = Calendar.getInstance();
		c1.setTime(new Date(time));
		// 当前日期
		Calendar c2 = Calendar.getInstance();
		c1.setTime(new Date(System.currentTimeMillis()));
		if (c1.get(Calendar.DAY_OF_YEAR) - 1 == c2.get(Calendar.DAY_OF_YEAR)) {
			if (c2.get(Calendar.HOUR_OF_DAY) >= 0
					&& c2.get(Calendar.HOUR_OF_DAY) <= 16) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}
}
